package com.DHH.Controller.Capital;

import com.DHH.Controller.Api.UserApiController;
import com.DHH.Dto.*;
import com.DHH.Entity.Base.BaseUser;
import com.DHH.Entity.Capital.CapitalSecurityGivebackRecord;
import com.DHH.Entity.Capital.CapitalSecurityGivebackState;
import com.DHH.Mapper.Capital.CapitalSecurityGivebackRecordMapper;
import com.DHH.Mapper.Capital.CapitalSecurityGivebackStateMapper;
import com.DHH.Service.Capital.ICapitalSecurityGivebackRecordService;
import com.DHH.Util.ReflectionUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


/**
 * Created by Administrator on 2017/4/15.
 */
@Controller
@RequestMapping("Admin/Capital/CapitalSecurityGivebackRecord")
public class CapitalSecurityGivebackRecordController {
    private Logger logger= LoggerFactory.getLogger(CapitalSecurityGivebackRecordController.class);
    @Autowired
    private CapitalSecurityGivebackRecordMapper capitalSecurityGivebackRecordMapper;
    @Autowired
    private ICapitalSecurityGivebackRecordService capitalSecurityGivebackRecordService;
    @Autowired
    private CapitalSecurityGivebackStateMapper capitalSecurityGivebackStateMapper;

    @Autowired
    private UserApiController userApiController;

    @RequestMapping("/listPage")
    public String listPage(HttpSession session,ModelMap modelMap){
        List<CapitalSecurityGivebackState> givebackStateList=capitalSecurityGivebackStateMapper.selectAll();
        modelMap.put("givebackStateList",givebackStateList);
        return "admin/capitalSecurityGivebackRecord/listCapitalSecurityGivebackRecordPage.jsp";
    }
    @RequestMapping("/addPage")
    public String addPage(HttpSession session,ModelMap modelMap){
            return "admin/capitalSecurityGivebackRecord/addCapitalSecurityGivebackRecordPage.jsp";
    }
    @RequestMapping("/updatePage")
    public String updatePage(HttpSession session,@RequestParam Integer id,ModelMap modelMap)
    {
        return "admin/capitalSecurityGivebackRecord/update{className}Page.jsp";
    }
    @RequestMapping("/detailsPage")
    public String detailPage(HttpSession session,@RequestParam Integer id,ModelMap modelMap)
    {
            return "admin/capitalSecurityGivebackRecord/detailsCapitalSecurityGivebackRecordPage.jsp";
    }

        @RequestMapping("/add")
        @ResponseBody
        public Message add(@Valid CapitalSecurityGivebackRecord capitalSecurityGivebackRecord,BindingResult result)
        {      Message msg = new Message();
                   if (result.hasErrors()) {
                          List<FieldError> err = result.getFieldErrors();
                           for (FieldError fe : err) {
                           msg.addError(fe.getField().toString(), fe.getDefaultMessage());
                            }
                     return msg;
                  }

         try{
                capitalSecurityGivebackRecord=capitalSecurityGivebackRecordService.insertCapitalSecurityGivebackRecord(capitalSecurityGivebackRecord);
                msg.setMsg("添加成功!");
                msg.setData(capitalSecurityGivebackRecord);
                msg.setState(true);
                return msg;
                }catch (Exception e)
                 {   msg.setMsg("操作失败!");
                    return msg;
                 }
        }
        @RequestMapping("/saveOrUpdate")
        @ResponseBody
        public Message saveOrUpdate(@Valid CapitalSecurityGivebackRecord capitalSecurityGivebackRecord,BindingResult result)
        {      Message msg = new Message();
        if (result.hasErrors()) {
        List<FieldError> err = result.getFieldErrors();
        for (FieldError fe : err) {
        msg.addError(fe.getField().toString(), fe.getDefaultMessage());
        }
        return msg;
        }
        try{
        capitalSecurityGivebackRecord=capitalSecurityGivebackRecordService.saveOrUpdateCapitalSecurityGivebackRecord(capitalSecurityGivebackRecord);
        msg.setMsg("添加成功!");
        msg.setData(capitalSecurityGivebackRecord);
        msg.setState(true);
        return msg;
        }catch (Exception e)
        {   msg.setMsg("操作失败!");
        return msg;
        }
        }
    @RequestMapping("/delete")
    @ResponseBody
    public Message delete(@RequestParam Integer id)
    {
        Message msg=new Message();
        try{
        	CapitalSecurityGivebackRecord capitalSecurityGivebackRecord=new CapitalSecurityGivebackRecord();
        	capitalSecurityGivebackRecord.setId(id);
            capitalSecurityGivebackRecord=capitalSecurityGivebackRecordService.deleteCapitalSecurityGivebackRecord(capitalSecurityGivebackRecord);
            msg.setMsg("操作成功");
            msg.setState(true);
            msg.setData(capitalSecurityGivebackRecord);
            return msg;
        }catch (Exception e)
        {   msg.setMsg("操作失败");
            return msg;
        }
    }
    //后台确认退回押金
    @RequestMapping("/update")
    @ResponseBody
    public Message update(CapitalSecurityGivebackRecord capitalSecurityGivebackRecord,HttpSession session)
    {   System.out.println("请求成功");
        Message msg=new Message();
        try{
//            BaseUser baseUser= (BaseUser) session.getAttribute(Constant.USER_IDENTIFICATION);
//            capitalSecurityGivebackRecord.setOperateId(baseUser.getId());
//            capitalSecurityGivebackRecord.setOperateTime(new Date());
//            msg.setData(capitalSecurityGivebackRecordService.updateCapitalSecurityGivebackRecord(capitalSecurityGivebackRecord));
            ApiBikeMessage apiBikeMessage=userApiController.depositRefund(capitalSecurityGivebackRecord,session);
            if(apiBikeMessage.getStatus()==1){
                msg.setMsg("操作成功！");
                msg.setState(true);
                return msg;
            }else{
                msg.setMsg(apiBikeMessage.getMessage());
                msg.setState(false);
                return msg;
            }

        }catch (Exception e)
        {   e.printStackTrace();
            msg.setMsg("操作失败，请稍后重试");
            return msg;
        }
    }
    @ResponseBody
    @RequestMapping("/query")
    public PageInfo<CapitalSecurityGivebackRecord> query(QueryInfo queryInfo) {
        System.err.println("--------------查询参数---------------");
        System.err.println(queryInfo);
        System.err.println("--------------查询参数---------------");
        /*为查询设置统一分页条件和排序条件*/
        PageHelper.startPage(queryInfo.getCurrentPage(), queryInfo.getPageSize());
        PageHelper.orderBy("create_time desc");
        if(queryInfo.getType()==null)
        {
            queryInfo.setType("search");
        }
        if(queryInfo.getCurrentPage()==null)
        {
            queryInfo.setCurrentPage(1);
        }
        if(queryInfo.getPageSize()==null)
        {
            queryInfo.setPageSize(10);
        }
        try{
            if(queryInfo.getType().equals("screen"))
             {
                   return this.screen(queryInfo);
             }
             if(queryInfo.getType().equals("filter"))
            {

                   return this.searchFilter(queryInfo);
            }
             return this.search(queryInfo);
        }catch (Exception e)
        {
            PageInfo<CapitalSecurityGivebackRecord> p=new PageInfo<CapitalSecurityGivebackRecord>();
            e.printStackTrace();
            p.setMsg("查询失败，请稍后重试！");
            return p;
        }

    }



    /**
     * 查询
     * @param queryInfo
     * @return
     */
    private PageInfo<CapitalSecurityGivebackRecord> search(QueryInfo queryInfo)
    {   System.out.println("---------\n"+queryInfo);
        PageInfo<CapitalSecurityGivebackRecord> pageInfo =new PageInfo<CapitalSecurityGivebackRecord>();
        CapitalSecurityGivebackRecord capitalSecurityGivebackRecord=new CapitalSecurityGivebackRecord();
            /*在这里设置相关的查询参数*/

        BaseUser baseUser=new BaseUser();
        baseUser.setIdentity("%"+queryInfo.getSearchKey()+"%");
        capitalSecurityGivebackRecord.setBaseUser(baseUser);
        Page<CapitalSecurityGivebackRecord> page = (Page<CapitalSecurityGivebackRecord>) capitalSecurityGivebackRecordMapper.searchByCapitalSecurityGivebackRecord(capitalSecurityGivebackRecord);
        pageInfo.setRows(page.getResult());
        pageInfo.setTotalRow(page.getTotal());
        pageInfo.setCurrentPage(queryInfo.getCurrentPage());
       return pageInfo;
    }

    /**
     * 筛选
     * @param queryInfo
     * @return
     */
    private  PageInfo<CapitalSecurityGivebackRecord> screen(QueryInfo queryInfo) {
    	PageInfo<CapitalSecurityGivebackRecord> pageInfo=new PageInfo< CapitalSecurityGivebackRecord>();
    	 CapitalSecurityGivebackRecord capitalSecurityGivebackRecord=new  CapitalSecurityGivebackRecord();
        for (String key : queryInfo.getMap().keySet()) {
               ReflectionUtils.setFieldValue(capitalSecurityGivebackRecord,key,queryInfo.getMap().get(key));
        }
        Page<CapitalSecurityGivebackRecord> page = (Page<CapitalSecurityGivebackRecord>) capitalSecurityGivebackRecordMapper.screenByCapitalSecurityGivebackRecord(capitalSecurityGivebackRecord);
        pageInfo.setRows(page.getResult());
        pageInfo.setTotalRow(page.getTotal());
        pageInfo.setCurrentPage(queryInfo.getCurrentPage());
        return pageInfo;
    }

    /**
     * 过滤
     * @param queryInfo
     * @return
     */
    private PageInfo<CapitalSecurityGivebackRecord> searchFilter(QueryInfo queryInfo) throws ParseException {    CapitalSecurityGivebackRecord capitalSecurityGivebackRecord=new  CapitalSecurityGivebackRecord();
    	PageInfo<CapitalSecurityGivebackRecord> pageInfo=new PageInfo< CapitalSecurityGivebackRecord>();
        FilterQuery filterQuery = new FilterQuery();
        filterQuery.setStartValue(queryInfo.getFilterStartValue());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        filterQuery.setEndValue(sdf.format(new Date(sdf.parse(queryInfo.getFilterEndValue()).getTime() + 24 * 3600 * 1000)));
        Page<CapitalSecurityGivebackRecord> page = (Page<CapitalSecurityGivebackRecord>)capitalSecurityGivebackRecordMapper.filterByCapitalSecurityGivebackRecord(filterQuery);
        pageInfo.setRows(page.getResult());
        pageInfo.setTotalRow(page.getTotal());
        pageInfo.setCurrentPage(queryInfo.getCurrentPage());
        return pageInfo;
    }
}

